<?php
class DausachesController extends AppController {

	var $name = 'Dausaches';
   	var $helpers=array('Html','Form','Js');
	var $components = array('RequestHandler','Cookie');
	var $uses = array('Dausach','Giaodichmuontra');
	
	function index() {
		$this->Dausach->recursive = 0;
		$this->set('dausaches', $this->paginate());
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid dausach', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('dausach', $this->Dausach->read(null, $id));
	}

	function add() {
		if (!empty($this->data)) {
			$this->Dausach->create();
			if ($this->Dausach->save($this->data)) {
				$this->Session->setFlash(__('The dausach has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The dausach could not be saved. Please, try again.', true));
			}
		}
		$linhvucs = $this->Dausach->Linhvuc->find('list',array('fields'=>'Linhvuc.tenlv'));
		$ngonnguks = $this->Dausach->Ngonnguk->find('list',array('fields'=>'Ngonnguk.tennn'));
		$nhaxuatbans = $this->Dausach->Nhaxuatban->find('list',array('fields'=>'Nhaxuatban.tennxb'));
		$this->set(compact('linhvucs', 'ngonnguks', 'nhaxuatbans'));
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid dausach', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Dausach->save($this->data)) {
				$this->Session->setFlash(__('The dausach has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The dausach could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Dausach->read(null, $id);
		}
		$linhvucs = $this->Dausach->Linhvuc->find('list');
		$ngonnguks = $this->Dausach->Ngonnguk->find('list');
		$nhaxuatbans = $this->Dausach->Nhaxuatban->find('list');
		$this->set(compact('linhvucs', 'ngonnguks', 'nhaxuatbans'));
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for dausach', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Dausach->delete($id)) {
			$this->Session->setFlash(__('Dausach deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Dausach was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}

	function timkiem()
    {
        $data=$this->data;
        $isAjax=0;
        if($this->RequestHandler->isAjax())
        {
        	$isAjax=1;
        		$subconor = array();
        		$subcon = array();
        		$conditions = array();
        		if(!empty($this->data['Dausach']['tensach']))
        		{
        			if($this->data['Dausach']['checkten']==1)
        				$subconor['Dausach.tensach LIKE'] = '%'.$this->data['Dausach']['tensach'].'%';
        			else
        				$subcon['Dausach.tensach LIKE']='%'.$this->data['Dausach']['tensach'].'%';
        		}
        		if(!empty($this->data['Dausach']['tacgia']))
        		{
        			if($this->data['Dausach']['checktg']==1)
        				$subconor['Dausach.tacgia LIKE'] = '%'.$this->data['Dausach']['tacgia'].'%';
        			else
        				$subcon['Dausach.tacgia LIKE']= '%'.$this->data['Dausach']['tacgia'].'%';
        		}
        		if(!empty($this->data['Dausach']['nxb']))
        		{
        			if($this->data['Dausach']['checknxb']==1)
        				$subconor['Nhaxuatban.tennxb LIKE'] = '%'.$this->data['Dausach']['nxb'].'%';
        			else
        				$subcon['Nhaxuatban.tennxb LIKE']='%'.$this->data['Dausach']['nxb'].'%';
        		}
        		if(!empty($this->data['Dausach']['linhvuc']))
        		{
        			
        			if($this->data['Dausach']['checklv']==1)
        				$subconor['Linhvuc.tenlv LIKE'] = '%'.$this->data['Dausach']['linhvuc'].'%';
        			else
        				$subcon['Linhvuc.tenlv LIKE']= '%'.$this->data['Dausach']['linhvuc'].'%';
        		}
        		if(!empty($this->data['Dausach']['ngonngu']))
        		{
        		
        			if($this->data['Dausach']['checknn']==1)
        				$subconor['Ngonnguk.tennn LIKE'] = '%'.$this->data['Dausach']['ngonngu'].'%';
        			else
        				$subcon['Ngonnguk.tennn LIKE']= '%'.$this->data['Dausach']['ngonngu'].'%';
        		}
        		if(!empty($subconor))
        		{
        			$conditions['OR']=$subconor; 
        			$conditions['OR'][] = $subcon;
        		}
        		else
        		{
        			$conditions = $subcon;
        		}
        		$joins = array();
        		if($this->data['Dausach']['sort']=='sachmoi' ||$this->data['Dausach']['sort']=='sachcu')
        		{
        			$joins =array(array('table' => 'chitietnhaps'
	            						,'type' => 'INNER'
	            						,'alias' => 'Chitietnhap'
	            						,'conditions' => array(
	                					'Chitietnhap.dausach_id = Dausach.id'))
        			,array('table' => 'hoadonnhaps'
	            						,'type' => 'INNER'
	            						,'alias' => 'Hoadonnhap'
	            						,'conditions' => array(
	                					'Chitietnhap.hoadonnhap_id = Hoadonnhap.id')));
	            	$order =array('Hoadonnhap.ngaynhap '.($this->data['Dausach']['sort']=='sachmoi'?'DESC':'ASC'));
        		}
        		else
        		{
        			$order =array('Dausach.'.$this->data['Dausach']['sort'].' '.$this->data['Dausach']['thutu']);
        		}
        		
        		if(!empty($conditions))
        		{
        			$this->Session->write('cons_search',$conditions);
        			$this->Session->write('data',$this->data);
        			$this->Dausach->recursive=2;
                	$this->paginate=array('joins'=>$joins,'order'=>$order,'conditions'=>$conditions);
                	$dausaches = $this->paginate();
        		}
        		
                $this->set(compact('dausaches'));
        }
        else
        {
        	$conditions =$this->Session->read('cons_search');
        	$this->data =  $this->Session->read('data');
        	if(!empty($conditions))
        	{
        	$joins = array();
        		if($this->data['Dausach']['sort']=='sachmoi' ||$this->data['Dausach']['sort']=='sachcu')
        		{
        			$joins =array(array('table' => 'chitietnhaps'
	            						,'type' => 'INNER'
	            						,'alias' => 'Chitietnhap'
	            						,'conditions' => array(
	                					'Chitietnhap.dausach_id = Dausach.id'))
        			,array('table' => 'hoadonnhaps'
	            						,'type' => 'INNER'
	            						,'alias' => 'Hoadonnhap'
	            						,'conditions' => array(
	                					'Chitietnhap.hoadonnhap_id = Hoadonnhap.id')));
	            	$order =array('Hoadonnhap.ngaynhap '.($this->data['Dausach']['sort']=='sachmoi'?'DESC':'ASC'));
        		}
        		else
        		{
        			$order =array('Dausach.'.$this->data['Dausach']['sort'].' '.$this->data['Dausach']['thutu']);
        		}
                	$this->Dausach->recursive=2;
                	$this->paginate=array('joins'=>$joins,'order'=>$order,'conditions'=>$conditions);
                	$dausaches = $this->paginate();
        	}
            $this->set(compact('dausaches'));
        }
      $this->set('isAjax',$isAjax);
    }

	function autocompletetensach()
	{
		$this->layout='ajax';		
		$textsearch = strtolower($this->params['url']['term']);
		$this->Dausach->displayField='tensach';
		$dausachs = $this->Dausach->find('list',array('conditions'=>array('tensach LIKE'=>'%'.$textsearch.'%')));
		$result = array();
		foreach ($dausachs as $key=>$value)
			array_push($result, array("id"=>$key, "value" => $value));
		
	$result=array_to_json($result);
	$this->set(compact('result'));
	$this->render('autocomplete');
	}
    
	function autocompletenxb()
	{
		$this->layout='ajax';		
		$textsearch = strtolower($this->params['url']['term']);
		$this->Dausach->Nhaxuatban->displayField='tennxb';
		$nxbs = $this->Dausach->Nhaxuatban->find('list',array('conditions'=>array('tennxb LIKE'=>'%'.$textsearch.'%')));
		$result = array();
		foreach ($nxbs as $key=>$value)
			array_push($result, array("id"=>$key, "value" => $value));
		
	$result=array_to_json($result);
	$this->set(compact('result'));
	$this->render('autocomplete');
	}
	
	function autocompletelv()
	{
		$this->layout='ajax';
		
		$textsearch = strtolower($this->params['url']['term']);
		$this->Dausach->Linhvuc->displayField='tenlv';
		$lvs = $this->Dausach->Linhvuc->find('list',array('conditions'=>array('tenlv LIKE'=>'%'.$textsearch.'%')));
		$result = array();
		foreach ($lvs as $key=>$value)
			array_push($result, array("id"=>$key, "value" => $value));
		
	$result=array_to_json($result);
	$this->set(compact('result'));
	$this->render('autocomplete');
	}

	function autocompletenn()
	{
		$this->layout='ajax';
		
		$textsearch = strtolower($this->params['url']['term']);
		$this->Dausach->Ngonnguk->displayField='tennn';
		$nns = $this->Dausach->Ngonnguk->find('list',array('conditions'=>array('tennn LIKE'=>'%'.$textsearch.'%')));
		$result = array();
		foreach ($nns as $key=>$value)
			array_push($result, array("id"=>$key, "value" => $value));
		
	$result=array_to_json($result);
	$this->set(compact('result'));
	$this->render('autocomplete');
	}

	
	// OR (`Dausach`.`tacgia` LIKE '%e%')
}

	function array_to_json( $array )
	{

	    if( !is_array( $array ) ){
	        return false;
	    }
	
	    $associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
	    if( $associative ){
	
	        $construct = array();
	        foreach( $array as $key => $value ){
	
	            // We first copy each key/value pair into a staging array,
	            // formatting each key and value properly as we go.
	
	            // Format the key:
	            if( is_numeric($key) ){
	                $key = "key_$key";
	            }
	            $key = "\"".addslashes($key)."\"";
	
	            // Format the value:
	            if( is_array( $value )){
	                $value = array_to_json( $value );
	            } else if( !is_numeric( $value ) || is_string( $value ) ){
	                $value = "\"".addslashes($value)."\"";
	            }
	
	            // Add to staging array:
	            $construct[] = "$key: $value";
	        }
	
	        // Then we collapse the staging array into the JSON form:
	        $result = "{ " . implode( ", ", $construct ) . " }";
	
	    } else { // If the array is a vector (not associative):
	
	        $construct = array();
	        foreach( $array as $value ){
	
	            // Format the value:
	            if( is_array( $value )){
	                $value = array_to_json( $value );
	            } else if( !is_numeric( $value ) || is_string( $value ) ){
	                $value = "'".addslashes($value)."'";
	            }
	
	            // Add to staging array:
	            $construct[] = $value;
	        }
	
	        // Then we collapse the staging array into the JSON form:
	        $result = "[ " . implode( ", ", $construct ) . " ]";
	    }
	
	    return $result;
	}

?>